package com.qqtech.qquan.order.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.homemaking.service.HomemakingOrderService;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.model.MallShopVo;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderConst;
import com.qqtech.qquan.order.enums.OrderDeliverySendDeliveryTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderDeliveryTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderPayWayDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderBaseQuery;
import com.qqtech.qquan.order.model.OrderBaseVo;
import com.qqtech.qquan.order.model.OrderCoupon;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.model.OrderPayLogQuery;
import com.qqtech.qquan.order.model.OrderPayLogVo;
import com.qqtech.qquan.order.service.OrderBaseService;
import com.qqtech.qquan.order.service.OrderCouponService;
import com.qqtech.qquan.order.service.OrderDeliveryService;
import com.qqtech.qquan.order.service.OrderHandleService;
import com.qqtech.qquan.order.service.OrderItemService;
import com.qqtech.qquan.order.service.OrderPayLogService;
import com.qqtech.qquan.order.service.OrderSysDictService;
import com.qqtech.qquan.sales.enums.SalesBaseSubsidyTypeDictEnum;
import com.qqtech.qquan.sales.enums.SalesBaseTypeDictEnum;
import com.qqtech.qquan.sales.model.SalesBase;
import com.qqtech.qquan.sales.service.SalesBaseService;
import com.qqtech.qquan.send.model.SendDeliveryUserOrder;
import com.qqtech.qquan.send.service.SendDeliveryUserOrderService;
import com.qqtech.qquan.sys.controller.BaseAgentController;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.sys.model.SysParam;
import com.qqtech.qquan.sys.service.SysDictService;
import com.qqtech.qquan.sys.service.SysParamService;
import com.qqtech.qquan.user.enums.UserIdentityTypeDictEnum;
import com.qqtech.qquan.user.model.UserAuth;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.model.UserIdentity;
import com.qqtech.qquan.user.model.UserIdentityQuery;
import com.qqtech.qquan.user.service.UserAuthService;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserIdentityService;
import com.qqtech.qquan.util.ExcelUtil;

@Controller
@RequestMapping(value = "/order/base")
public class OrderBaseController extends BaseAgentController {

	@Resource
	private OrderBaseService orderBaseService;

	@Resource
	private OrderDeliveryService orderDeliveryService;

	@Resource
	private OrderItemService orderItemService;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private HomemakingOrderService homemakingOrderService;

	@Resource
	private MallShopService mallShopService;
	@Resource
	private OrderSysDictService orderSysDictService;
	@Resource
	private SysDictService sysDictService;

	@Resource
	private UserAuthService userAuthService;
	@Resource
	private UserIdentityService userIdentityService;
	@Resource
	private SendDeliveryUserOrderService sendDeliveryUserOrderService;
	@Resource
	private OrderHandleService orderHandleService;
	@Resource
	private SysParamService sysParamService;
	@Resource
	private CommunityBaseService communityBaseService;

	@Resource
	private OrderPayLogService orderPayLogService;
	@Resource
	private OrderCouponService orderCouponService;
	@Resource
	private SalesBaseService salesBaseService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		return "/order/orderbase-list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(OrderBaseQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		query.setCommunityId(super.getCurrCommunityId());//当前后台用户的社区id
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "newAt"));
		Page<OrderBaseVo> page = orderBaseService.queryPageListAdmin(query, pageKit);
		List<OrderBaseVo> orderList = page.getContent();
		if (orderList != null && orderList.size() > 0) {
			for (OrderBaseVo orderVo : orderList) {
				setPayValueIn3Mode(orderVo);// 附上【圈币、微信或者支付宝各支付了多少】、优惠券情况、商家总额、满减活动
			}
		}
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	@RequestMapping(value = "/detail")
	public String detail(OrderBaseQuery orderBaseQuery, Model model) {
		OrderBaseVo order = null;
		MallShopVo shop = null;
		if (orderBaseQuery.getId() != null) {
			order = orderBaseService.getById(orderBaseQuery.getId());
		} else {
			order = orderBaseService.getByOrderNo(orderBaseQuery.getOrderNo());
		}
		if (order != null) {
			OrderDelivery delivery = orderDeliveryService.getByOrderNo(order.getOrderNo());
			List<OrderItem> itemList = orderItemService.findByOrderNo(order.getOrderNo());
			if (OrderBaseOrderTypeDictEnum.QUANMALL.getCode() == order.getOrderType().intValue()
					|| OrderBaseOrderTypeDictEnum.QSHOP.getCode() == order.getOrderType().intValue()) {
				shop = mallShopService.getById(order.getShopId());
				if (shop != null && shop.getCommunityId() != null && shop.getCommunityId().intValue() != 0) {
					CommunityBaseVo communityBase = communityBaseService.getById(shop.getCommunityId());
					if (communityBase != null) {
						shop.setCommunityName(communityBase.getName());
					}
				}
				model.addAttribute("shop", shop);
				model.addAttribute("sellerName", shop.getName());
				model = getSendDelivery(order, delivery, shop, model);
			} else {
				if (order.getSellerId() != null && order.getSellerId().intValue() != 0) {
					UserBase seller = userBaseService.getById(order.getSellerId());
					model.addAttribute("sellerName", seller.getNick());
				}
			}
			UserBase buyer = userBaseService.getById(order.getBuyerId());
			if (order.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode()) {
				model.addAttribute("homemakingOrder", homemakingOrderService.getByOrderNo(order.getOrderNo()));
			}
			setPayValueIn3Mode(order);// 附上【圈币、微信或者支付宝各支付了多少】
			model.addAttribute("order", order);
			model.addAttribute("itemList", itemList);
			model.addAttribute("delivery", delivery);
			model.addAttribute("buyerName", buyer.getNick());
		}
		return "/order/orderbase-detail";
	}

	/**
	 * 获取订单配送信息
	 * 
	 * @param order
	 * @param result
	 * @return
	 */
	public Model getSendDelivery(OrderBaseVo order, OrderDelivery delivery, MallShop shop, Model model) {
		String deliveryType = "";
		String sendDeliveryName = "";// 配送员名称
		String sendDeliveryPhone = "";// 配送员电话
		if (order.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QUANMALL.getCode()
				|| order.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()) {

			if (delivery.getType().intValue() == OrderDeliveryTypeDictEnum.SELLERSEND.getCode()) { // 非自提
				if (order.getDeliveryStatus().intValue() != OrderBaseDeliveryStatusDictEnum.UNSEND.getCode()) { // 已经发货
					if (delivery.getHasNeedDelivery().intValue() == YesNoEnum.NO.getCode()) { // 配送
						if (delivery.getSendDeliveryType().intValue() == OrderDeliverySendDeliveryTypeDictEnum.QUANQUAN
								.getCode()) {// 圈圈配送
							deliveryType = "圈圈配送";
							SendDeliveryUserOrder sendDeliveryUserOrder = sendDeliveryUserOrderService
									.getByOrderNo(order.getOrderNo());
							if (sendDeliveryUserOrder != null && sendDeliveryUserOrder.getDeliveryUserId() != null) {
								UserAuth sendDeliveryUserAuth = userAuthService
										.getByUserId(sendDeliveryUserOrder.getDeliveryUserId());
								if (sendDeliveryUserAuth != null) {
									sendDeliveryName = sendDeliveryUserAuth.getRealName();// 配送人员真实姓名
								}
								UserIdentityQuery uiq = new UserIdentityQuery();
								uiq.setSize(1);
								uiq.setUserId(sendDeliveryUserOrder.getDeliveryUserId());
								uiq.setType(UserIdentityTypeDictEnum.PHONE.getCode());
								UserIdentity userIdentity = userIdentityService.getOne(uiq);
								if (userIdentity != null && userIdentity.getIdentity() != null) {
									sendDeliveryPhone = userIdentity.getIdentity();
								}
							}
						} else { // 商家配送
							deliveryType = "商家配送";
							sendDeliveryName = shop.getName() + "店主";
							sendDeliveryPhone = shop.getPhone();
						}
					} else {
						// 物流
					}
				} else {
					deliveryType = "配送";
				}
			} else if (delivery.getType().intValue() == OrderDeliveryTypeDictEnum.BUYERPICKUP.getCode()) { // 自提
				deliveryType = "买家自提";
			}
		}
		model.addAttribute("deliveryType", deliveryType);
		model.addAttribute("sendDeliveryName", sendDeliveryName);
		model.addAttribute("sendDeliveryPhone", sendDeliveryPhone);
		return model;
	}

	@RequestMapping(value = "/export2Excel")
	@ResponseBody
	public Result export2Excel(OrderBaseQuery query, HttpServletRequest request, HttpServletResponse response) {
		Result ret = new Result();
		query.setCommunityId(super.getCurrCommunityId());//当前后台用户的社区id
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "newAt"));
		int count = orderBaseService.queryCount(query);
		SysParam sysParam = sysParamService.getByKey(SysConst.PARAM_SYS_EXPORT_TOEXCEL_MAXROWS);
		if (sysParam != null && StringUtil.isNotBlank(sysParam.getValue())) {
			int maxExportRows = Integer.valueOf(sysParam.getValue());
			if (count > maxExportRows) {
				ret.addErr("导出数量不能超过" + maxExportRows + "行!");
				return ret;
			}
		}
		List<OrderBaseVo> orderList = orderBaseService.queryList4Excel(query, pageKit);// 不分页
		if (orderList != null && orderList.size() > 0) {
			for (OrderBaseVo orderVo : orderList) {
				setPayValueIn3Mode(orderVo);
			}
		}
		List<Map<String, Object>> list = createExcelRecord(orderList);
		String columnNames[] = { "订单号", "订单名称", "社区名称","业务类型", "是否外部供应商订单", "买方", "卖方", "订单原价", "卖家收入", "优惠券支付", "圈圈满减",
				"商家满减", "余额支付", "圈币支付", "支付宝支付", "微信支付", "订单状态", "支付状态", "收发货状态", "签收类型", "下单时间" };// 列名
		String keys[] = { "orderNo", "title", "communityName", "orderType", "isExternal", "buyerNick", "sellerNick", "originalTotal",
				"sellerTotal", "couponPay", "salesQuanStr", "salesShopStr", "cashPay", "quanPay", "aliPay", "weixinPay",
				"orderStatus", "payStatus", "deliveryStatus", "deliveryStatusSignType", "strNewAt" };// map中的key
		String fileName = "订单表";
		ExcelUtil.ExcelSingleOutputStream(list, keys, columnNames, fileName, request, response);
		return ret;
	}

	private List<Map<String, Object>> createExcelRecord(List<OrderBaseVo> orderList) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "订单");
		listmap.add(map);
		OrderBaseVo order = null;

		for (int j = 0; j < orderList.size(); j++) {
			order = orderList.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("orderNo", order.getOrderNo());
			mapValue.put("title", order.getTitle());
			mapValue.put("communityName", order.getCommunityName());
			mapValue.put("orderType", orderSysDictService.dictValue(OrderConst.DICTYPE_ORDER_BASE_ORDERTYPE,
					String.valueOf(order.getOrderType())));
			mapValue.put("buyerNick", order.getBuyerNick());
			mapValue.put("sellerNick", order.getSellerNick());
			mapValue.put("originalTotal", order.getOriginalTotal());
			mapValue.put("sellerTotal", order.getSellerTotal());
			mapValue.put("couponPay", order.getCouponPay());
			mapValue.put("salesQuanStr", order.getSalesQuanStr());
			mapValue.put("salesShopStr", order.getSalesShopStr());
			mapValue.put("cashPay", order.getCashPay());
			mapValue.put("quanPay", order.getQuanPay());
			mapValue.put("aliPay", order.getAliPay());
			mapValue.put("weixinPay", order.getWeixinPay());
			mapValue.put("orderStatus", orderSysDictService.dictValue(OrderConst.DICTYPE_ORDER_BASE_ORDERSTATUS,
					String.valueOf(order.getOrderStatus())));
			mapValue.put("payStatus", orderSysDictService.dictValue(OrderConst.DICTYPE_ORDER_BASE_PAYSTATUS,
					String.valueOf(order.getPayStatus())));
			mapValue.put("strNewAt", order.getStrNewAt());
			mapValue.put("isExternal", order.getIsExternal() == null ? "" : (order.getIsExternal() == 1 ? "是" : "否"));
			mapValue.put("deliveryStatus", orderSysDictService.dictValue(OrderConst.DICTYPE_ORDER_BASE_DELIVERYSTATUS,
					String.valueOf(order.getDeliveryStatus())));
			mapValue.put("deliveryStatusSignType",
					orderSysDictService.dictValue(OrderConst.DICTYPE_ORDER_BASE_DELIVERYSTATUS_SIGNTYPE,
							String.valueOf(order.getDeliveryStatusSignType())));
			listmap.add(mapValue);
		}
		return listmap;
	}

	/**
	 * 后台管理人员取消订单
	 * 
	 * @param orderBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/adminCancel")
	@ResponseBody
	public Result adminCancel(@RequestBody OrderBaseQuery orderBaseQuery) {
		Result result = new Result();
		String orderNo = "";
		if (orderBaseQuery == null || orderBaseQuery.getId() == null) {
			result.addErr("参数OrderNo不能为空");
		} else {
			OrderBase orderbase = orderBaseService.getById(orderBaseQuery.getId());
			if (orderbase != null) {
				orderNo = orderbase.getOrderNo();
			} else {
				result.addErr("该订单不存在");
			}
			if (orderbase != null
					&& orderbase.getOrderStatus().intValue() != OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode()) {
				result.addErr("当前订单状态不能取消");
			}
		}
		if (result.checkForm()) {
			result = orderHandleService.adminCancel(orderNo);
		}
		return result;
	}

	/**
	 * 后台管理人员审核订单同意退款
	 * 
	 * @param orderBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/adminAgreeReturnPay")
	@ResponseBody
	public Result adminAgreeReturnPay(@RequestBody OrderBaseQuery orderBaseQuery) {
		Result result = new Result();
		String orderNo = "";
		if (orderBaseQuery == null || orderBaseQuery.getId() == null) {
			result.addErr("参数OrderNo不能为空");
		} else {
			OrderBase orderbase = orderBaseService.getById(orderBaseQuery.getId());
			if (orderbase != null) {
				orderNo = orderbase.getOrderNo();
			} else {
				result.addErr("该订单不存在");
			}
			if (orderbase != null
					&& orderbase.getOrderStatus().intValue() != OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode()) {
				result.addErr("当前订单交易完成，不能退款");
			}
		}
		if (result.checkForm()) {
			result = orderHandleService.adminAgreeReturnPay(orderNo);
		}
		return result;
	}

	/**
	 * 后台管理人员审核订单拒绝退款
	 * 
	 * @param orderBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/adminRefuseReturnPay")
	@ResponseBody
	public Result adminRefuseReturnPay(@RequestBody OrderBaseQuery orderBaseQuery) {
		Result result = new Result();
		if (orderBaseQuery.getId() == null) {
			result.addErr("订单不存在");
			return result;
		}
		OrderBase orderbase = orderBaseService.getById(orderBaseQuery.getId());
		result = orderHandleService.sellerRefuseReturnPay(orderbase.getOrderNo());
		return result;
	}

	/**
	 * 附上4种支付方式的支付金额【支付方式:1-圈币;2-支付宝;3-微信;4-余额】，另加优惠券支付和满减情况
	 * 
	 * @param orderVo
	 */
	private void setPayValueIn3Mode(OrderBaseVo orderVo) {
		OrderPayLogQuery query = new OrderPayLogQuery();
		query.setOrderNo(orderVo.getOrderNo());
		BigDecimal quanPay = BigDecimal.ZERO;
		BigDecimal cashPay = BigDecimal.ZERO;
		BigDecimal aliPay = BigDecimal.ZERO;
		BigDecimal weixinPay = BigDecimal.ZERO;
		BigDecimal couponPay = BigDecimal.ZERO;
		StringBuffer salesQuanSB = new StringBuffer();
		StringBuffer salesShopSB = new StringBuffer();

		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "id"));
		List<OrderPayLogVo> payLogList = orderPayLogService.queryList(query, pageKit);
		if (payLogList != null && payLogList.size() > 0) {
			for (OrderPayLogVo payLog : payLogList) {
				if (payLog.getPayWay() == OrderPayWayDictEnum.QUAN.getCode()) {
					quanPay = quanPay.add(payLog.getValue());
				}
				if (payLog.getPayWay() == OrderPayWayDictEnum.MONEY.getCode()) {
					cashPay = cashPay.add(payLog.getValue());
				} else if (payLog.getPayWay() == OrderPayWayDictEnum.ALIPAY.getCode()) {
					aliPay = aliPay.add(payLog.getValue());
				} else if (payLog.getPayWay() == OrderPayWayDictEnum.WEIXIN.getCode()) {
					weixinPay = weixinPay.add(payLog.getValue());
				}
			}
			orderVo.setQuanPay(quanPay);
			orderVo.setCashPay(cashPay);
			orderVo.setAliPay(aliPay);
			orderVo.setWeixinPay(weixinPay);
		}
		// 增加优惠券支付情况
		if (StringUtil.isNotBlank(orderVo.getOrderNo())) {
			OrderCoupon orderCoupon = new OrderCoupon();
			orderCoupon.setOrderNo(orderVo.getOrderNo());
			List<OrderCoupon> listOrderCoupon = orderCouponService.queryList(orderCoupon);
			if (listOrderCoupon != null && listOrderCoupon.size() > 0) {
				for (OrderCoupon orderCoupon2 : listOrderCoupon) {
					if (orderCoupon2.getMinusPrice() != null) {
						couponPay = couponPay.add(orderCoupon2.getMinusPrice());
					}
				}
			}
		}
		orderVo.setCouponPay(couponPay);
		// 判断满减活动情况
		if (StringUtil.isNotBlank(orderVo.getSalesId())) {
			String[] salseIdArr = orderVo.getSalesId().split(";");
			if (salseIdArr != null && salseIdArr.length > 0) {
				for (String string : salseIdArr) {
					SalesBase salesBase = salesBaseService.getById(new Integer(string));
					if (salesBase != null && salesBase.getType() != null
							&& SalesBaseTypeDictEnum.REBATE.getCode() == salesBase.getType().intValue()) {
						if (salesBase.getSubsidyType() != null && salesBase.getSubsidy() != null
								&& salesBase.getSubsidy().compareTo(BigDecimal.ZERO) != 0) {
							if (salesBase.getSubsidyType().intValue() == SalesBaseSubsidyTypeDictEnum.QUAN.getCode()) {
								if (StringUtil.isNotBlank(salesBase.getName())) {
									if (StringUtil.isNotBlank(salesQuanSB.toString())) {
										salesQuanSB.append(";");
									}
									salesQuanSB.append(salesBase.getName());
								}
							} else {
								if (StringUtil.isNotBlank(salesShopSB.toString())) {
									salesShopSB.append(";");
								}
								salesShopSB.append(salesBase.getName());
							}
						}
					}
				}
			}
		}
		if (StringUtil.isBlank(salesQuanSB.toString())) {
			salesQuanSB.append("");
		}
		if (StringUtil.isBlank(salesShopSB.toString())) {
			salesShopSB.append("");
		}
		orderVo.setSalesQuanStr(salesQuanSB.toString());
		orderVo.setSalesShopStr(salesShopSB.toString());
	}
}
